package hd.util;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;

import java.util.ArrayList;

/**
 * Service工具
 * <p/>
 * Created by apple on 14/10/20.
 */
public class ServiceUtil {

    private static Context mContext;

    /**
     * 使用此类里面其他函数的之前必须先初始化此函数
     *
     * @param context 上下文
     */
    public static void init(Context context) {
        mContext = context;
    }

    /**
     * 判断某个service 是否在运行
     *
     * @param service 服务
     * @return bool
     */
    public static boolean isRunning(String service) {
        ActivityManager myManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager.getRunningServices(30);
        for (ActivityManager.RunningServiceInfo aRunningService : runningService) {
            if (aRunningService.service.getClassName().equals(service)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 开启某个服务
     *
     * @param c Class<ServiceClassName>
     */
    public static void run(Class<?> c) {
        Intent intent = new Intent(mContext, c);
        mContext.startService(intent);
    }

    /**
     * 停止一个服务
     *
     * @param c Class<ServiceClassName>
     */
    public static void stop(Class<?> c) {
        Intent intent = new Intent(mContext, c);
        mContext.stopService(intent);
    }
}